/**
 * promise状态
 * PENDING：等待
 * FULFILLED：成功
 * REJECTED：失败
 * @type {{FULFILLED: string, PENDING: string, REJECTED: string}}
 */
const PROMISE_STATE = {
    PENDING: 'pending',
    FULFILLED: 'fulfilled',
    REJECTED: 'rejected'
}

class PromiseWheel {
    constructor(executor) {
        this.currentStatus = PROMISE_STATE.PENDING;
        this.value = undefined;
        this.reason = undefined;
        executor(this.resolve, this.reject)
    }

    resolve = (value) => {
        if(this.currentStatus != PROMISE_STATE.PENDING){return}
        this.currentStatus = PROMISE_STATE.FULFILLED;
        this.value = value;
        this.onFulfilled(value);
    }

    reject = (reason) => {
        if(this.currentStatus != PROMISE_STATE.PENDING){return}
        this.currentStatus = PROMISE_STATE.REJECTED;
        this.reason = reason;
        this.onRejected(reason);
    }

    then = (resolveCallback, rejectCallback) => {
        if (this.currentStatus == PROMISE_STATE.PENDING) {
            this.onFulfilled = resolveCallback;
            this.onRejected = rejectCallback;
        }else if (this.currentStatus == PROMISE_STATE.FULFILLED) {
            resolveCallback(this.value);
        } else if (this.currentStatus == PROMISE_STATE.REJECTED) {
            rejectCallback(this.reason);
        }
    }
}

new PromiseWheel((resolve, reject) => {
    setTimeout(() => {
        // resolve('成功了')
        reject('失败了')
    }, 100);
}).then(
    resp => {
        console.log(resp)
    },
    resp => {
        console.log(resp)
    })
